package mutsumimod.patches;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.evacipated.cardcrawl.modthespire.lib.*;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.EnergyManager;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import javassist.CannotCompileException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
import mutsumimod.monitors.CopyMonitor;

public class CopyWithTargetPatch extends BasePatch {


    @SpirePatch(
            clz=AbstractCard.class,
            method = "hasEnoughEnergy"
    )
    public static class hasEnoughEnergyFixPatch {
        @SpirePrefixPatch
        public static SpireReturn<Boolean> prefix(AbstractCard __instance) {
            if(CopyPatch.AbstractCardFieldPatch.inChoosingTarget.get(__instance)){
                return SpireReturn.Return(true);
            }
            return SpireReturn.Continue();
        }
    }

    @SpirePatch(
            clz=AbstractPlayer.class,
            method = "useCard",
            paramtypez = {
                    AbstractCard.class, AbstractMonster.class, int.class
            }
    )
    public static class useCardFixPatch {
        @SpirePostfixPatch
        public static void postfix(AbstractPlayer __instance,AbstractCard c, AbstractMonster monster, int energyOnUse) {
            //CopyPatch.AbstractCardFieldPatch.inCopyUse.set(c, false);
            CopyPatch.AbstractCardFieldPatch.inChoosingTarget.set(c, false);
            CopyMonitor.clearCopyCard();
        }
    }

    @SpirePatch(
            clz = AbstractPlayer.class,
            method = "useCard",
            paramtypez = {
                    AbstractCard.class, AbstractMonster.class, int.class
            }
    )
    public static class CopyEnergyPatch {
        @SpireInstrumentPatch
        public static ExprEditor Instrument() {
            return new ExprEditor() {
                @Override
                public void edit(MethodCall m) throws CannotCompileException {
                    if (m.getClassName().equals(EnergyManager.class.getName())
                            && m.getMethodName().equals("use")) {
                        m.replace("{ "
                                + CopyEnergyPatch.class.getName()
                                + ".copyEnergyUse($0,c); }");
                    }
                }
            };
        }

        public static void copyEnergyUse(EnergyManager energy, AbstractCard c) {
            if(!CopyPatch.AbstractCardFieldPatch.inChoosingTarget.get(c)){
                energy.use(c.costForTurn);
            }
        }
    }

}
